package com.dldata.devtools30.controller.sysform;


import com.dldata.devtools30.entity.DevtFormListtemplateEntity;
import com.dldata.devtools30.entity.DevtFormTypeEntity;
import com.dldata.devtools30.service.sysform.DevtFormListTemplateService;
import com.dldata.devtools30.service.sysform.DevtFormTypeService;
import com.dldata.devtools30.utils.Result;
import com.dldata.devtools30.utils.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**

 */
@Controller
@RequestMapping(value = "/DevtFormTypeController")
public class DevtFormTypeController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DevtFormTypeService customFormTypeService;
    @Autowired
    DevtFormListTemplateService sysCrfFormListTemplateService;



    @RequestMapping(value = "/getAll")
    @ResponseBody
    public Result getAllCustomType(String search){

        if(StringUtil.isEmptyOrLength0(search)){
            search="";
        }
        search="%"+search+"%";

        List <DevtFormTypeEntity> customTypeEntityList = customFormTypeService.getAllFormType(search);

        return Result.ok(customTypeEntityList) ;
    }


    private List<LayuiTreeNode> parseSubType(List<DevtFormTypeEntity> customTypeEntityList, LayuiTreeNode fType, List<LayuiTreeNode> treeNodesFrom, String typeId, String cancel) {
        List<LayuiTreeNode> treeNodes=new LinkedList<>();
        customTypeEntityList.stream().filter(
                sysCrfFormTypeEntity ->
                (StringUtil.isEmptyOrLength0(fType) && (sysCrfFormTypeEntity.getfTypeId() == null || sysCrfFormTypeEntity.getfTypeId().equals("") || sysCrfFormTypeEntity.getfTypeId().equals("0")))
                || (!StringUtil.isEmptyOrLength0(fType) && (fType.getId().equals(sysCrfFormTypeEntity.getfTypeId())))
        ).forEach(sysCrfFormTypeEntity1 -> {
            LayuiTreeNode layuiTreeNode = new LayuiTreeNode();
            layuiTreeNode.setId(sysCrfFormTypeEntity1.getId());
            layuiTreeNode.setMid(sysCrfFormTypeEntity1.getfTypeId());
            layuiTreeNode.setName(sysCrfFormTypeEntity1.getName());
            layuiTreeNode.setText(sysCrfFormTypeEntity1.getName());
            layuiTreeNode.setSpread(layuiTreeNode.getId().equals(typeId));
            layuiTreeNode.setState(layuiTreeNode.getId().equals(typeId)?"open":"closed");
            layuiTreeNode.setCode(sysCrfFormTypeEntity1.getName());
            layuiTreeNode.setMname(fType==null?"":fType.getName());
            if(sysCrfFormTypeEntity1.getCancel()==null?false:sysCrfFormTypeEntity1.getCancel()){
                layuiTreeNode.setText(sysCrfFormTypeEntity1.getName()+"[已作废]");
//                layuiTreeNode.setState("closed");
            }
            layuiTreeNode.setNodeType("type");
            treeNodes.add(layuiTreeNode);

            parseSubType(customTypeEntityList,layuiTreeNode,treeNodesFrom,typeId,cancel);
            boolean isc = false;
            if("1".equals(cancel)&&sysCrfFormTypeEntity1.getCancel()){
                //查看未作废数据，当作废状态为true时，从结果中排除数据
                isc = true;
            }
            if("0".equals(cancel)&&!sysCrfFormTypeEntity1.getCancel()&&layuiTreeNode.getChildren().size()==0){
                //查看已作废数据，当作废状态为false时且子元素为空，从结果中排除数据
                isc = true;
            }
            if(isc){
                treeNodes.remove(layuiTreeNode);
            }
        });
        if(treeNodes.size()==0){
            treeNodes.addAll(treeNodesFrom.stream().filter(layuiTreeNode -> layuiTreeNode.getType().equals(fType.getId())).collect(Collectors.toList()));
            treeNodes.stream().forEach(treeNode -> {
                treeNode.setMname(fType.getName());
            });
        }
        if(fType!=null){
            fType.setChildren(treeNodes);
            fType.setState(treeNodes.size()==0?"open":"closed");
            fType.setState(fType.getId().equals(typeId)?"open":"closed");
        }
        return treeNodes;
    }

    @RequestMapping(value = "save")
    @ResponseBody
    public Result save(DevtFormTypeEntity sysCrfFormTypeEntity, HttpServletRequest request, HttpServletResponse response) throws  Exception{

        String result;
        try {
            if (sysCrfFormTypeEntity.getId()==null||sysCrfFormTypeEntity.getId().equals("")) {
                sysCrfFormTypeEntity.setId(UUID.randomUUID().toString());
                List<DevtFormTypeEntity> customFormTypeEntities = new ArrayList<DevtFormTypeEntity>();
                customFormTypeEntities = customFormTypeService.findByTypeIdXh(sysCrfFormTypeEntity.getId(), sysCrfFormTypeEntity.getXh());
                if (customFormTypeEntities.size() > 0) {

                    return Result.error("序号已存在！");
                }

                sysCrfFormTypeEntity.setfTypeId("0");
            }
            if(sysCrfFormTypeEntity.getfTypeId()==null){
                sysCrfFormTypeEntity.setfTypeId("");
            }

            customFormTypeService.save(sysCrfFormTypeEntity);
            return Result.ok();


        } catch (Exception ex) {
            result = "{\"success\":false,\"msg\":\"操作错误，请稍候再试！\"}";
            logger.error("【执行" + this.getClass().getName() + ".save() 方法失败 】异常：" + ex.getMessage(),ex);
            return Result.error("操作错误，请稍候再试！");
        }

    }

    @RequestMapping("delete")
    @ResponseBody
    public Result delete(String id,HttpServletRequest request, HttpServletResponse response) throws Exception{
        String result;

        List<DevtFormListtemplateEntity> sysCrfFormEntities=sysCrfFormListTemplateService.getDataByFl(id,"");
        if(sysCrfFormEntities.size()>0){

            return Result.error("分类下有表单,请删除表单后再删除分类！");
        }
        try {
            customFormTypeService.deleteOne(id);

            return Result.ok();
        }
        catch (Exception ex){

            logger.error("【执行"+this.getClass().getName()+".delete() 方法失败 】异常："+ex.getMessage());
            return Result.error("操作错误，请稍候再试！");
        }

    }


    public static class LayuiTreeNode{

        private String name;

        private String code;

        private String id;

        /**
         * 父ID
         */
        private String mid;

        /**
         * 父名称
         */
        private String mname;

        private String type;

        private String nodeType;

        private boolean spread;

        private String text;

        private boolean checked=false;

        private String state="open";

        private List<LayuiTreeNode> children=new LinkedList<>();

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getMid() {
            return mid;
        }

        public void setMid(String mid) {
            this.mid = mid;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getNodeType() {
            return nodeType;
        }

        public void setNodeType(String nodeType) {
            this.nodeType = nodeType;
        }

        public boolean isSpread() {
            return spread;
        }

        public void setSpread(boolean spread) {
            this.spread = spread;
        }

        public List<LayuiTreeNode> getChildren() {
            return children;
        }

        public void setChildren(List<LayuiTreeNode> children) {
            this.children = children;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMname() {
            return mname;
        }

        public void setMname(String mname) {
            this.mname = mname;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public boolean isChecked() {
            return checked;
        }

        public void setChecked(boolean checked) {
            this.checked = checked;
        }

        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }
    }
}
